﻿using CloudStorageLight.Core;
using CloudStorageLight.Core.Web;
using CloudStorageLight.SharePointWeb.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
using Microsoft.Owin.Security;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DropNet;
using System.Threading;

namespace CloudStorageLight.SharePointWeb.Controllers
{
    public class HomeController : FilesControllerBase
    {

        protected override BlobService CreateBlobService()
        {
            //BasicAuthenticateUtil.Init();
            return new BlobService();
        }


        protected override BlobUser GetCurrentUser()
        {
            if (_user == null)
            {
                _user = BasicAuthenticateUtil.GetCurrentUser();
            }
            return _user;
        }
        private BlobUser _user;


        [AllowAnonymous]
        public ActionResult Root()
        {
            if (!this.HttpContext.User.Identity.IsAuthenticated) return Redirect("~/Account/Login");
            if (SystemSettings.Instance.MultiDomain)
            {
                var account = BlobService.GetCurrentCloudAccount();
                if (account == null)
                {
                    var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

                    if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
                    {
                        var ticket = FormsAuthentication.Decrypt(authCookie.Value);
                        if (!string.IsNullOrEmpty(ticket.UserData))
                        {
                            var url = Url.RouteUrl("files", new { domain = ticket.UserData, id = "/" });
                            return Redirect(url);
                        } 
                    }
                    return Redirect("~/Account/Login");
                }
                else
                {
                    var url = Url.RouteUrl("files", new { domain = account.AccountName, id = "/" });
                    return Redirect(url);
                }
            }
            else
            {
                var url = Url.RouteUrl("files", new { id = "/" });
                return Redirect(url);
            }
        }


        //[SharePointContextFilter]
        public override async Task<ActionResult> Index(string id = "", string snapshot = "current", string mode = null, string baseVersion=null, string passcode = null, System.Web.Mvc.FormCollection fc =null)
        {
            //後ろ空白トリム対策
            var rootPath = Url.RouteUrl("files", new { id = "" });
            if (this.Request.Url.AbsolutePath.Length > rootPath.Length + 1)
            {
                id = BlobUtil.UnescapeDataString(this.Request.Url.AbsolutePath.Substring(rootPath.Length + 1));
            }

            //if (!HttpContext.User.Identity.IsAuthenticated) TrySpLogin();
            if (id == "" && !this.HttpContext.User.Identity.IsAuthenticated) return RedirectToAction("Login", "Account");
            if (!this.HttpContext.User.Identity.IsAuthenticated && !await CreateBlobService().CanReadAsync(GetCurrentUser(), "/" + id.TrimStart('/')))
            {
                return RedirectToAction("Login", "Account", new { returnUrl = Request.Url.ToString() });
            }
            if (SystemSettings.Instance.MultiDomain)
            {
                var queryString = new RouteValueDictionary();
                foreach (var item in this.Request.QueryString.AllKeys)
                {
                    queryString.Add(item ?? "", this.Request[item]);
                }
                var domain = BlobService.GetCurrentDomain();
                if (string.IsNullOrEmpty(domain))
                {
                    var cloudAcccout = CloudAccount.LoadBySpHostUrl(SystemSettings.Instance.BlobStorage, SharePointContext.GetSPHostUrl(this.Request).AbsoluteUri);
                    if (cloudAcccout == null) return RedirectToAction("CreateCloudAccount", "Account", queryString);
                    queryString.Add("domain", cloudAcccout.AccountName);
                    return RedirectToAction("Index", "Home", queryString);
                }
            }
            return await base.Index(id, snapshot, mode, baseVersion, passcode, fc);
        }

    }
}
